package com.gitbl.webchat.web.control;

import com.alibaba.fastjson.JSONObject;
import com.gitbl.webchat.service.RoomService;
import com.gitbl.webchat.service.UserService;
import com.gitbl.webchat.utils.RedisHelper;
import com.gitbl.webchat.web.webmessage.WebUser;
import jdk.nashorn.internal.objects.annotations.Property;
import jdk.nashorn.internal.parser.Token;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class BaseController {
    protected static UserService userService;
    protected static RoomService roomService;
    public static void init(UserService userService, RoomService roomService){
        BaseController.userService = userService;
        BaseController.roomService = roomService;
    }
    protected final static String A_USER="user";
    final static int TOKEN_TIME_OUT=3600*4;
    final static private ShardedJedisPool redispool;
    static{
        String shosts = System.getProperty("session.hosts");
        if(shosts==null||shosts.equals(""))
            shosts="127.0.0.1:6379";
        String[] hostsadd= shosts.split(",");
        redispool = RedisHelper.newPool(hostsadd);
    }
    final static String KEY_TOKEN_PRE = "token.";
    final static String KEY_USER_PRE = "user.";
    <T> T getObject(String key,Class<T> c){
        ShardedJedis r = redispool.getResource();
        try {
            String s = r.get(key);
            if (s == null) {
                return null;
            }
            return JSONObject.parseObject(s, c);
        }finally {
            r.close();
        }
    }
    <T> T getAndExpire(String key,Class<T> c,int sec){
        ShardedJedis r = redispool.getResource();
        try {
            String s = r.get(key);
            if (s == null) {
                return null;
            }
            r.expire(key,sec);
            return JSONObject.parseObject(s, c);
        }finally {
            r.close();
        }
    }
    protected ShardedJedis newShardedJedis(){
        return redispool.getResource();
    }

    protected WebUser getUser(HttpServletRequest request){
        return (WebUser) request.getAttribute(A_USER);
    }

    protected WebUser getUserByToken(String token){
        //获取刷新超时时间
        return getAndExpire(KEY_TOKEN_PRE+token,WebUser.class,TOKEN_TIME_OUT);
    }

    protected String getToken(String username){
        return getObject(KEY_USER_PRE+username,String.class);
    }
}
